package yto.freemarker.springbootstudy.cglib;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class CglibProxy implements MethodInterceptor {

    private Enhancer enhancer = new Enhancer();

    public <T> T getInstance(Class<T> clazz) {
        enhancer.setSuperclass(clazz);
        enhancer.setCallback(this);
        T o = (T) enhancer.create();
        return o;
    }

    /**
     * Object为由CGLib动态生成的代理类实例
     * Method为上文中实体类所调用的被代理的方法引用
     * Object[]为参数值列表
     * MethodProxy为生成的代理类对方法的代理引用。
     *
     * @param o
     * @param method
     * @param objects
     * @param methodProxy
     * @return
     * @throws Throwable
     */
    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {

        System.out.println("前置增强！！");
        Object o1 = methodProxy.invokeSuper(o, objects);

        System.out.println("后置增强!!");
        return o1;
    }
}